package org.wanho.shop.servlet;

import org.wanho.shop.entity.Order;
import org.wanho.shop.entity.User;
import org.wanho.shop.service.OrderService;
import org.wanho.shop.service.impl.OrderServiceImpl;
import org.wanho.shop.vo.Cart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-04-27 9:55
 * Description：<描述>
 */
@WebServlet("*.order")
public class OrderServlet extends HttpServlet {

    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/create.order".equals(path)){
            create(req,resp);
        }else if("/findMyOrders.order".equals(path)){
            findMyOrders(req,resp);
        }else if("/findDetail.order".equals(path)){
            findDetail(req,resp);
        }
    }

    private void findDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Order order = orderService.findDetail(id);
        req.setAttribute("order",order);
        req.getRequestDispatcher("/jsp/orderDetail.jsp").forward(req,resp);
    }

    private void findMyOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");

        List<Order> orders = orderService.findMyOrders(user);
        req.setAttribute("orders",orders);
        req.getRequestDispatcher("/jsp/myOrders.jsp").forward(req,resp);
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        User user = (User) req.getSession().getAttribute("user");

        String no = orderService.create(cart, user);
        // 清空购物车
        req.getSession().setAttribute("cart", new Cart());
        req.getSession().setAttribute("no",no);
        resp.sendRedirect(req.getContextPath()+"/jsp/success.jsp");

    }
}
